<template>
	<view class="read-box">
		<view class="status-bar" :style="{ height: iStatusBarHeight + 'px'}"></view>
		<u-navbar title="阅读时间">
			<view class="slot-wrap">
				<u-icon name="reload" size="40" style="margin-right: 20rpx;"></u-icon>
				<u-icon name="zhuanfa" size="40" style=""></u-icon>
			</view>
		</u-navbar>
		<!-- 阅读量图 -->
		<view class="">
			<view class="chart-title">
				<text>阅读时间</text>
			</view>
			<!--#ifndef MP-ALIPAY -->
			<canvas canvas-id="canvasGauge" id="canvasGauge" class="charts"></canvas>
			<!--#endif-->
		</view>
		<!--关键词图-->
		<view>
			<view class="chart-title">
				<text>阅读关键词</text>
			</view>
			<!--#ifndef MP-ALIPAY -->
			<canvas canvas-id="canvasWord" id="canvasWord" class="charts"></canvas>
			<!--#endif-->
		</view>
		<!-- 阅读时段表 -->
		<view>
			<view class="chart-title">
				<text>阅读时段</text>
			</view>
			<!--#ifndef MP-ALIPAY -->
			<canvas canvas-id="canvasColumn" id="canvasColumn" class="charts" height='200px'></canvas>
			<!--#endif-->
		</view>
		<!-- 类型分布 -->
		<view>
			<view class="chart-title">
				<text>阅读类型</text>
			</view>
			<!--#ifndef MP-ALIPAY -->
			<canvas canvas-id="canvasPie" id="canvasPie" class="charts" @touchstart="touchPie"></canvas>
			<!--#endif-->
		</view>
		<!-- 阅读排行 -->
		<view>
			<view class="chart-title">
				<text>阅读排行</text>
			</view>
			<!--#ifdef MP-ALIPAY -->
			<canvas canvas-id="canvasFunnel" id="canvasFunnel" class="charts" :width="cWidth*pixelRatio" :height="cHeight*pixelRatio"
			 :style="{'width':cWidth+'px','height':cHeight+'px'}" @touchstart="touchFunnel"></canvas>
			<!--#endif-->
			<!--#ifndef MP-ALIPAY -->
			<canvas canvas-id="canvasFunnel" id="canvasFunnel" class="charts" @touchstart="touchFunnel"></canvas>
			<!--#endif-->
		</view>
	</view>
</template>

<script>
	import uCharts from '@/components/u-charts/u-charts.js';
	var _self;
	var canvaGauge = null;
	var canvaWord = null;
	var canvaColumn = null;
	var canvasPie = null;
	var canvasFunnel = null;
	export default {
		data() {
			return {
				cWidth: '',
				cHeight: '',
				pixelRatio: 1,
				textarea: '',
				gaugeWidth: 15,
				type: 'default',
				readTimeList: [],
				bookList: [],
				readTime: 0,
				endNumber: 100
			}
		},
		onLoad() {
			_self = this;
			//#ifdef MP-ALIPAY
			uni.getSystemInfo({
				success: function(res) {
					if (res.pixelRatio > 1) {
						_self.pixelRatio = 2;
					}
				}
			});
			//#endif
			this.cWidth = uni.upx2px(650);
			this.cHeight = uni.upx2px(580);
			this.getBookList();
			this.getReadTimeStorage().then(() => {
				this.getReadTime();
				this.getKeywords();
				this.getReadTimeCount();
				this.getBookType();
				this.getReadRank();
			})
		},
		methods: {
			getBookList() {
				let bookList = uni.getStorageSync('bookList');
				if (bookList) {
					let _bookList = JSON.parse(bookList)
					this.bookList = _bookList;
				}
			},

			getReadTimeStorage() {
				return new Promise((resolve, reject) => {
					let read_time = uni.getStorageSync('read_time');
					if (read_time) {
						this.readTimeList = JSON.parse(read_time);
						resolve('ok')
					}
				})
			},
			// 获取阅读时间
			getReadTimeRequest() {
				return new Promise((resolve, reject) => {
					let readTime = 0;
					if (this.readTimeList.length !== 0) {
						this.readTimeList.forEach(item => {
							readTime += this.getTime(item.readTimeStart, item.readTimeEnd)
						})
						let min = Math.floor((readTime / 1000 / 60) << 0);
						resolve(min)
					}
				})
			},
			getTime(start, end) {
				return new Date(end).getTime() - new Date(start).getTime()
			},
			getReadTime() {
				this.getReadTimeRequest().then(res => {
					_self.endNumber = res < 100 && res > 0 ? 100 : res < 1000 ? 1000 : res < 10000 ? 10000 : 100000;
					let Gauge = {
						"categories": [{
							"value": 0.2,
							"color": "#1890ff"
						}, {
							"value": 0.8,
							"color": "#2fc25b"
						}, {
							"value": 1,
							"color": "#f04864"
						}],
						"series": [{
							"name": "阅读时间",
							"data": res / _self.endNumber
						}]
					};
					_self.textarea = JSON.stringify(Gauge);
					_self.showGauge("canvasGauge", Gauge);
				})
			},
			showGauge(canvasId, chartData) {
				canvaGauge = new uCharts({
					$this: _self,
					canvasId: canvasId,
					type: 'gauge',
					fontSize: 11,
					legend: {
						show: false
					},
					title: {
						name: Math.round(chartData.series[0].data * 100) + '分钟',
						color: chartData.categories[0].color,
						fontSize: 30 * _self.pixelRatio,
						offsetY: 0, //新增参数，自定义调整Y轴文案距离
					},
					subtitle: {
						name: chartData.series[0].name,
						color: '#666666',
						fontSize: 15 * _self.pixelRatio,
						offsetY: 0, //新增参数，自定义调整Y轴文案距离
					},
					extra: {
						gauge: {
							type: 'progress',
							width: _self.gaugeWidth * _self.pixelRatio, //仪表盘背景的宽度
							startAngle: 0.75,
							endAngle: 0.25,
							startNumber: 0,
							endNumber: 1,
							splitLine: {
								fixRadius: 0,
								splitNumber: 10,
								width: _self.gaugeWidth * _self.pixelRatio, //仪表盘背景的宽度
								color: '#FFFFFF',
								childNumber: 5,
								childWidth: _self.gaugeWidth * 0.4 * _self.pixelRatio, //仪表盘背景的宽度
							},
							pointer: {
								width: _self.gaugeWidth * 0.8 * _self.pixelRatio, //指针宽度
								color: 'auto'
							}
						}
					},
					background: '#FFFFFF',
					pixelRatio: _self.pixelRatio,
					categories: chartData.categories,
					series: chartData.series,
					animation: true,
					width: _self.cWidth * _self.pixelRatio,
					height: _self.cHeight * _self.pixelRatio,
					dataLabel: true,
				});
			},

			getKeywordsRequest() {
				return new Promise((resolve, reject) => {
					let KeywordsList = [];
					if (this.readTimeList.length !== 0) {
						this.readTimeList.forEach(item => {
							KeywordsList = [...KeywordsList, ...this.getKeywordsById(item.bookId)]
						})
						KeywordsList.forEach(item => {
							if (item.name.length > 14) {
								item.name = item.name.slice(0, 13)
							}
						})
						let _keywordList = _.unionBy(KeywordsList, 'name')
						resolve(_keywordList)
					}
				})
			},
			getKeywordsById(id) {
				let keywords = [{
						name: this.bookList[id].intro,
						textSize: Math.floor(Math.random() * (25 - 15 + 1) + 15),
					},
					{
						name: this.bookList[id].is_over,
						textSize: Math.floor(Math.random() * (25 - 15 + 1) + 15),
					},
					{
						name: this.bookList[id].name,
						textSize: Math.floor(Math.random() * (25 - 15 + 1) + 15),
					},
					{
						name: this.bookList[id].type,
						textSize: Math.floor(Math.random() * (25 - 15 + 1) + 15),
					},
					{
						name: this.bookList[id].writer,
						textSize: Math.floor(Math.random() * (25 - 15 + 1) + 15),
					}
				]
				return keywords;
			},
			getKeywords() {
				this.getKeywordsRequest().then(res => {
					let Word = {
						series: res
					};
					_self.textarea = JSON.stringify(Word);
					_self.showWord("canvasWord", Word);
				});
			},
			showWord(canvasId, chartData) {
				canvaWord = new uCharts({
					$this: _self,
					canvasId: canvasId,
					type: 'word',
					background: '#ffffff',
					animation: true,
					pixelRatio: _self.pixelRatio,
					series: chartData.series,
					width: _self.cWidth * _self.pixelRatio,
					height: _self.cHeight * _self.pixelRatio,
					extra: {
						word: {
							type: 'normal'
						}
					}
				});
			},

			getReadTimeCount() {
				let Column = {
					"categories": ["0点~8点", "8点~16点", "16点~24点"],
					"series": [{
						"name": "阅读时间",
						"data": [35, 8, 25]
					}]
				};
				_self.textarea = JSON.stringify(Column);
				_self.showColumn("canvasColumn", Column);
			},
			showColumn(canvasId, chartData) {
				canvaColumn = new uCharts({
					$this: _self,
					canvasId: canvasId,
					type: 'column',
					fontSize: 11,
					padding: [5, 15, 15, 15],
					legend: {
						show: true,
						position: 'top',
						float: 'center',
						itemGap: 30,
						padding: 5,
						margin: 5,
						//backgroundColor:'rgba(41,198,90,0.2)',
						//borderColor :'rgba(41,198,90,0.5)',
						borderWidth: 1
					},
					dataLabel: true,
					dataPointShape: true,
					background: '#FFFFFF',
					pixelRatio: _self.pixelRatio,
					categories: chartData.categories,
					series: chartData.series,
					animation: true,
					enableScroll: true,
					xAxis: {
						disableGrid: false,
						type: 'grid',
						gridType: 'dash',
						itemCount: 4
					},
					yAxis: {
						//disabled:true
						gridType: 'dash',
						splitNumber: 4,
						min: 10,
						max: 480,
						format: (val) => {
							return val.toFixed(0) + '分钟'
						} //如不写此方法，Y轴刻度默认保留两位小数
					},
					width: _self.cWidth * _self.pixelRatio,
					height: _self.cHeight * _self.pixelRatio,
					extra: {
						column: {
							type: 'group',
							width: _self.cWidth * _self.pixelRatio * 0.45 / chartData.categories.length
						}
					},
				});
			},
			getBookTypeRequest() {
				return new Promise((resolve, reject) => {
					let typeList = [];
					let _readTimeList = _.unionBy(this.readTimeList, (item) => {
						return item.bookId
					})
					if (_readTimeList.length !== 0) {
						_readTimeList.forEach(item => {
							typeList.push({
								name: this.bookList[item.bookId].type
							})
						})
					}
					let _typeList = _.countBy(typeList, (item) => {
						return item.name
					})
					let list = [];
					Object.entries(_typeList).forEach(([key, value]) => {
						list.push({
							"name": key,
							"data": value
						})
					})
					resolve(list)
				})
			},
			getBookType() {
				this.getBookTypeRequest().then(res => {
					let Pie = {
						"series": res
					};
					_self.textarea = JSON.stringify(Pie);
					_self.showPie("canvasPie", Pie);
				});
			},
			showPie(canvasId, chartData) {
				canvasPie = new uCharts({
					$this: _self,
					canvasId: canvasId,
					type: 'ring',
					fontSize: 11,
					padding: [15, 15, 0, 15],
					legend: {
						show: true,
						padding: 5,
						lineHeight: 11,
						margin: 0,
					},
					title: {
						name: '阅读类型',
						color: '#7cb5ec',
						fontSize: 18,
						offsetY: -10,
					},
					subtitle: {
						name: chartData.series.length + '种',
						color: '#666666',
						fontSize: 15,
						offsetY: 10,
					},
					background: '#FFFFFF',
					pixelRatio: _self.pixelRatio,
					series: chartData.series,
					animation: true,
					width: _self.cWidth * _self.pixelRatio,
					height: _self.cHeight * _self.pixelRatio,
					dataLabel: true,
					extra: {
						pie: {
							type: 'area',
							minRadius: 50,
							activeOpacity: 0.5,
							offsetAngle: 0,
							labelWidth: 15
						}
					},
				});
			},
			touchPie(e) {
				canvasPie.showToolTip(e, {
					format: function(item) {
						return item.name + ':' + item.data + '本'
					}
				});
			},

			getReadRankRequest() {
				return new Promise((resolve, reject) => {
					let rankList = [];
					if (this.readTimeList.length !== 0) {
						this.readTimeList.forEach(item => {
							rankList.push({
								name: this.bookList[item.bookId].name,
								data: this.getTime(item.readTimeStart, item.readTimeEnd)
							})
						})
						let _rankList = _(rankList)
							.flatten()
							.groupBy('name')
							.map(_.spread((...values) => {
								return _.mergeWith(...values, (objValue, srcValue) => {
									if (_.isNumber(objValue)) {
										return objValue + srcValue;
									}
								});
							}))
							.value();
						resolve(_rankList)
					}
				})
			},

			getReadRank() {
				this.getReadRankRequest().then(res => {
					let Funnel = {
						"series": res
					}
					_self.textarea = JSON.stringify(Funnel);
					_self.showFunnel("canvasFunnel", Funnel);
				});
			},
			formatTime(mss) {
				let days = parseInt(mss / (1000 * 60 * 60 * 24)) === 0 ? '' : parseInt(mss / (1000 * 60 * 60 * 24)) + '天';
				let hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)) === 0 ? '' : parseInt((mss % (1000 * 60 * 60 *
					24)) / (1000 * 60 * 60)) + '小时';
				let minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60)) === 0 ? '' : parseInt((mss % (1000 * 60 * 60)) / (
					1000 * 60)) + '分钟';
				let seconds = (mss % (1000 * 60)) / 1000 === 0 ? '' : (mss % (1000 * 60)) / 1000 + '秒';
				return `${days}${hours}${minutes}${seconds}`
			},
			showFunnel(canvasId, chartData) {
				canvasFunnel = new uCharts({
					$this: _self,
					canvasId: canvasId,
					type: 'funnel',
					fontSize: 11,
					padding: [15, 15, 0, 15],
					legend: {
						show: true,
						padding: 5,
						lineHeight: 11,
						margin: 0,
					},
					background: '#FFFFFF',
					pixelRatio: _self.pixelRatio,
					series: chartData.series,
					animation: true,
					width: _self.cWidth * _self.pixelRatio,
					height: _self.cHeight * _self.pixelRatio,
					dataLabel: true,
					extra: {
						funnel: {
							border: true,
							borderWidth: 2,
							borderColor: '#FFFFFF'
						}
					},
				});
			},
			touchFunnel(e) {
				canvasFunnel.showToolTip(e, {
					format: function(item) {
						return item.name + ':' + _self.formatTime(item.data)
					}
				});
				canvasFunnel.touchLegend(e, {
					animation: true
				});
			}
		}
	}
</script>

<style>
	.read-box {
		background: #F5F8FC;
		min-height: 100vh;
		padding: 0rpx 5vw 20rpx 5vw;
	}

	.chart-title {
		margin: auto;
		background: white;
		padding: 20rpx;
		border-radius: 20rpx 20rpx 0 0;
	}

	.chart-title text {
		border-left: 8rpx solid #91c7ff;
		padding-left: 10rpx;
	}

	.charts {
		width: 90vw;
		height: 580upx;
		background-color: #FFFFFF;
		margin: auto;
		border-radius: 0 0 20rpx 20rpx;
		margin-bottom: 40rpx;
	}

	.status-bar {
		height: var(--status-bar-height);
		width: 100%;
		background: #F5F8FC;
	}

	.slot-wrap {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		width: 100%;
		padding: 0 20px;
	}
</style>
